package com.xltq.dao.impl;

import com.xltq.dao.IUserDao;
import com.xltq.entity.User;
import com.xltq.utils.C3P0Utils;
import com.xltq.utils.Constants;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

public class IUserDaoImpl implements IUserDao {
    private QueryRunner queryRunner = new QueryRunner();

    /**
     * 根据用户名查询用户是否存在
     *
     * @param username 用户名
     * @return 返回结果集封装在User实体类对象中
     * @throws Exception 定义抛出异常
     */
    @Override
    public User queryUserByName(String username) throws Exception {
        String sql = "select u_id as uid, u_name as username, u_password as upassword,u_email as email, u_sex as usex," +
                " u_status as ustatus, u_code as code, u_role as urole from user where u_name = ?";

        return queryRunner.query(C3P0Utils.getConnection(), sql, new BeanHandler<User>(User.class), username);
    }

    /**
     * 注册信息添加到 User表中(注册用户)
     *
     * @param user 封装数据的实体类
     * @return 受影响的行数
     * @throws Exception 定义抛出异常
     */
    @Override
    public int insertUser(User user) throws Exception {
        String sql = "insert into user(u_name, u_password, u_email, u_sex, u_status, u_code, u_role) values(?,?,?,?,?,?,?)";
        return queryRunner.update(C3P0Utils.getConnection(), sql, user.getUsername(), user.getUpassword(), user.getEmail(), user.getUsex(), user.getUstatus(), user.getCode(), user.getUrole());
    }

    /**
     * 通过注册码(激活码) 查询用户
     *
     * @param code 激活码
     * @return 查询到是 User对象信息
     * @throws Exception 定义抛出异常
     */
    @Override
    public User queryUserByCode(String code) throws Exception {
        String sql = "select u_id as uid, u_name as username, u_password as upassword,u_email as email, u_sex as usex," +
                " u_status as ustatus, u_code as code, u_role as urole from user where u_code = ?";
        return queryRunner.query(C3P0Utils.getConnection(), sql, new BeanHandler<User>(User.class), code);
    }

    /**
     * 通过查询激活码用户获取到用户信息 新型激活操作
     *
     * @param uid 用户id信息
     * @return 受影响函数
     * @throws Exception 定义抛出异常
     */
    @Override
    public int updateStatusByUid(int uid) throws Exception {
        String sql = "update user set u_status = ? where u_id = ?";
        return queryRunner.update(C3P0Utils.getConnection(), Constants.USER_ACTIVE, sql, uid);
    }

    /**
     * 通过用户名和密码进行查询
     *
     * @param username 用户名
     * @param password 密码
     * @return 查询到User集合
     * @throws Exception 定义抛出异常
     */
    @Override
    public User login(String username, String password) throws Exception {
        String sql = "select u_id uid, u_name  username, u_password upassword, u_email uemail, u_sex usex, u_status ustatus, u_code ucode, u_role urole from user where u_name = ? and u_password = ?;";
        return queryRunner.query(C3P0Utils.getConnection(), sql, new BeanHandler<User>(User.class), username, password);
    }
}
